package com.itheima.xmlparse;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class XmlParse {
    public static void main(String[] args) throws DocumentException {
        // 1. 获取 document 对象
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("xml/student.xml"));

        // 2. 获取根标签
        Element rootElement = document.getRootElement();
        // 3. 根据根标签获取student标签
//        List elements = rootElement.elements();
        List<Element> studentElements = rootElement.elements("student");

        ArrayList<Student> list = new ArrayList<>();
        for (Element element : studentElements) {
            // element 依次表示每一个 student 标签
            // 获取 id 这个属性
            Attribute attribute = element.attribute("id");
            // 获取 id 的属性值
            String id = attribute.getValue();
            // 获取 name 标签
            Element nameElement = element.element("name");
            // 获取标签体的内容
            String name = nameElement.getText();
            // 获取 age 这个标签
            Element ageElement = element.element("age");
            // 获取标签体的内容
            String age = ageElement.getText();

            Student stu = new Student(id, name, Integer.parseInt(age));
            list.add(stu);
        }

        for (Student student : list) {
            System.out.println(student);
        }
    }
}
